package com.util;

import java.security.Key;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;

public class DESUtil {
	Key key;

	public DESUtil() {

	}

	public DESUtil(String str) {
		setKey(str);
	}

	public Key getKey() {
		return key;
	}

	@SuppressWarnings("deprecation")
	public void setKey(String strKey) {
		byte[] result = new byte[8];
		strKey.getBytes(0, strKey.length(), result, 0);

        for (int i = 0; i < 8; i++)
        	result[i] = (byte)( ((result[i] & 0x01) << 7) |
                             ((result[i] & 0x02) << 5) |
                             ((result[i] & 0x04) << 3) |
                             ((result[i] & 0x08) << 1) |
                             ((result[i] & 0x10) >> 1) |
                             ((result[i] & 0x20) >> 3) |
                             ((result[i] & 0x40) >> 5) |
                             ((result[i] & 0x80) >> 7)  );
				
		try {
			KeyGenerator _generator = KeyGenerator.getInstance("DES");
			_generator.init(new SecureRandom(result));
			this.key = _generator.generateKey();
			_generator = null;
		} catch (Exception e) {
			throw new RuntimeException(
					"Error initializing SqlMap class. Cause: " + e);
		}
	}

	public byte[] EncryptByte(byte[] byteS) {
		byte[] byteFina = null;
		Cipher cipher;
		try {
			cipher = Cipher.getInstance("DES");
			cipher.init(Cipher.ENCRYPT_MODE, key);
			byteFina = cipher.doFinal(byteS);
		} catch (Exception e) {
			throw new RuntimeException(
					"Error initializing SqlMap class. Cause: " + e);
		} finally {
			cipher = null;
		}
		return byteFina;
	}

	public byte[] DecryptByte(byte[] byteD) {
		Cipher cipher;
		byte[] byteFina = null;
		try {
			cipher = Cipher.getInstance("DES");
			cipher.init(Cipher.DECRYPT_MODE, key);
			byteFina = cipher.doFinal(byteD);
		} catch (Exception e) {
			throw new RuntimeException(
			"Error initializing SqlMap class. Cause: " + e);
		} finally {
			cipher = null;
		}
		return byteFina;
	}
}